package com.ruoyi.system.util;


import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
public class SmsCodeUtil {

    @Autowired
    private RedisCache redisCache;

    private static final String SMS_CODE_PREFIX = "sms_code:";
    private static final String SMS_PWD_PREFIX = "sms_pwd:";
    // 1分钟过期时间
    private static final long EXPIRE_TIME = 10 * 60;


    /**
     * 保存密码到缓存
     *
     * @param pwd 密码
     */
    public void savePwd(String phone,String pwd) {
        redisCache.setCacheObject(SMS_PWD_PREFIX + phone, pwd, 30, TimeUnit.DAYS);
    }
    /**
     * 从缓存获取密码
     *
     * @param phone 手机号
     * @return
     */
    public String getPwd(String phone) {
        return redisCache.getCacheObject(SMS_PWD_PREFIX + phone);
    }

    /**
     * 生成随机验证码
     *
     * @return 6位数字验证码
     */
    public String generateCode() {
        return String.valueOf(new Random().nextInt(899999) + 100000);
    }

    /**
     * 保存验证码到缓存
     *
     * @param phoneNumber 手机号
     * @param code        验证码
     */
    public void saveCode(String phoneNumber, String code) {
        redisCache.setCacheObject(SMS_CODE_PREFIX + phoneNumber, code, EXPIRE_TIME, TimeUnit.SECONDS);
    }

    /**
     * 删除验证码到缓存
     *
     * @param phoneNumber 手机号
     */
    public void delCode(String phoneNumber) {
        redisCache.deleteObject(SMS_CODE_PREFIX + phoneNumber);
    }

    /**
     * 验证验证码
     *
     * @param phoneNumber 手机号
     * @param code        验证码
     * @return 是否验证成功
     */
    public boolean verifyCode(String phoneNumber, String code) {
        Object cacheObject = redisCache.getCacheObject(SMS_CODE_PREFIX + phoneNumber);
        String cacheCode = String.valueOf(cacheObject);
        return code.equals(cacheCode);
    }
}
